package com.heima.wemedia.service.impl;

import com.heima.api.IScheduleClientFeign;
import com.heima.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClientFeign scheduleClientFeign;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    /**
     * 添加任务到延迟队列中
     *
     * @param id          文章的id
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Override
    public void addNewsToTask(Integer id, Date publishTime) {
        //远程调用
        Task task=new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());

        //开始对参数进行序列化操作
        WmNews wmews=new WmNews();
        wmews.setId(id);
        byte[] bytes = ProtostuffUtil.serialize(wmews);

        task.setParameters(bytes);
        scheduleClientFeign.addTask(task);
    }

    /**
     * 消费延迟队列数据
     * 执行定时任务,每50s执行一次
     */
    @Override
    @Scheduled(fixedRate=50000)
    public void scanNewsByTask() {
        //调用feign接口
        Integer taskType=TaskTypeEnum.NEWS_SCAN_TIME.getTaskType();
        Integer priority=TaskTypeEnum.NEWS_SCAN_TIME.getPriority();
        Task task = scheduleClientFeign.pullTask(taskType, priority);
        if(task!=null){
            byte[] parameters = task.getParameters();
            if(parameters!=null && parameters.length>0){
                //反序列化操作
                WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
                //2.调用自动审核业务
                wmNewsAutoScanService.autoScanNews(wmNews.getId());
            }

        }

    }
}
